<?php
/**
 * 注册控制器
 * @Author   Wcj
 * @email 1054487195@qq.com
 * @DateTime 2019/7/17 17:28
 */

namespace app\index\controller;

use think\Controller;
use app\index\model\Member as MemberModel;
use think\Log;
use think\Queue;

class Register extends Controller
{
    /**
     * 渲染模板 展示注册页面
     * @return mixed
     */
    public function index()
    {
        exit('hello world');
    }

    /**
     * 执行注册逻辑
     * @Author   Wcj
     * @email 1054487195@qq.com
     * @DateTime 2019/7/22 17:11
     * @param MemberModel $memberModel
     * @return \think\response\Json
     */
    public function doRegister(MemberModel $memberModel)
    {
        $params = $this->request->post();

        $data = [
            'email' => $params['email'] ?? '10086@qq.com',
            'password' => $params['password'] ?? '123',
        ];

        //写入注册的用户
        $result = $memberModel->allowField(['email', 'password'])->save($data);
        if (empty($result)) return ajax(2, '注册失败');

        //注册完毕后获取到邮件账号  然后加入到队列
        $this->sendActivationMail($memberModel->email);
        return ajax(1, '注册成功,请前往邮箱激活您的账号!');
    }

    /**
     * @param string $email 邮箱账号
     */
    private function sendActivationMail($email = '')
    {
        $jobName = 'app\index\job\sendActivationMail';  // 负责处理队列任务的类
        $data = ['email' => $email]; // 当前任务所需的业务数据
        $jobQueueName = 'sendActivationMail'; // 当前任务归属的队列名称，如果为新队列，会自动创建

        // 将任务推送到消息队列等待对应的消费者去执行
        $result = Queue::push($jobName, $data, $jobQueueName);

        if ($result) {
            Log::record(date('Y-m-d H:i:s') . '-New task' . PHP_EOL);
        } else {
            Log::record(date('Y-m-d H:i:s') . '-Add queue error' . PHP_EOL);
        }
    }
}